<?php
/**
 * Created by PhpStorm.
 * User: Yangxufeng
 * Date: 2018/8/29
 * Time: 16:49
 */

namespace app\index\server;

use app\index\model\Notice as NoticeModel;
use app\lib\exception\DatabaseException;
use think\Exception;

class NoticeServer extends BaseServer
{
    public function getList($params = [])
    {
        $prep_params = $this->prep_param($params);
        try {
            $count = NoticeModel::count();
            $list = NoticeModel::order($prep_params['sort'], $prep_params['order'])
                ->limit($prep_params['offset'], $prep_params['limit'])
                ->select();
        } catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return bootstrap_table_return($count, $list);
    }

    public function addOrUpdate($params = [])
    {
        $data = [
            'contents' => $params['contents'],
            'start_time' => $params['start_time'],
            'end_time' => $params['end_time'],
            'sort' => $params['sort'],
            'status' => $params['status'],
        ];
        try{
            if(isset($params['primary_key'])){
                $result = NoticeModel::where('id', '=', $params['primary_key'])
                ->update($data);
            }else{
                $result = NoticeModel::insert($data);
            }
            if(!$result){
                return setMsg(0, '操作notice消息失败');
            }
        }catch(Exception $e){
            throw new DatabaseException([
               'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, '操作notice消息成功');
    }

    public function detail($id)
    {
        try{
            $detail = NoticeModel::where('id', '=', $id)->find();
            if(!$detail){
                return setMsg(0, '未找到notice数据');
            }
        }catch(Exception $e){
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, '成功查找到notice数据', $detail);
    }

    public function changeStatus($id)
    {
        try{
            $info = NoticeModel::where('id', '=', $id)->find();
            $info->status = abs( ($info->status) - 1 );
            $result = $info->save();
            if(!$result){
                return setMsg(0, '修改Notice状态失败');
            }
        }catch(Exception $e){
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, '修改Notice状态成功');
    }
}